// pages/edit-card/edit-card.js
const cardStyles = require("../../mock/data/cards"); // 名片模板样式
const utils = require("../../utils/util.js");
const cardCase = require("../../mock/data/card.js"); // 自测用填写数据
const cardFields = require("../../mock/data/card-template.js"); // 名片模板所有字段
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cardId: "", // 名片id 用于区分新增名片还是修改名片
    addIndex: 0,
    addList: ["电话", "传真", "子公司名称", "网址", "QQ", "邮编", "公司说明"],
    addListName: [
      "phone",
      "fax",
      "subCompName",
      "webSite",
      "qq",
      "postCode",
      "compDesc"
    ],
    currentCardIndex: 0,
    currentCard: {},
    cardStyles: cardStyles,
    nameStyle: "",
    positionStyle: "",
    mobileStyle: "",
    addressStyle: "",
    emailStyle: "",
    detail: cardFields,
    customCardPath: "",
    nickName: "",
    customCardImagePath: "",
    generatorCardImagePath: ""
  },
  addInfo(event) {
    console.log(event);
    const value = event.detail.value;
    const index = this.data.addListName[value];
    this.setData({
      ["detail." + index + ".show"]: true
    });
  },
  changeCardCase(event) {
    const index = event.currentTarget.dataset.index;
    const _this = this;
    if (index === "custom") {
      // 自己上传名片，则不需要更新信息，上传图片后把返回的地址插入到图片地址即可
      wx.chooseImage({
        count: 1,
        success: function(res) {
          console.log(res);
          wx.showLoading({
            mask: true,
            title: "正在识别中..."
          });
          utils
            .ajax(
              "/v1/bcs/uploadCustBusinessCard.do",
              {},
              {
                name: "businessCardFile",
                path: res.tempFiles[0].path
              }
            )
            .then(res => {
              wx.hideLoading();
              if (res.code === "000000") {
                _this.setData({
                  customCardImagePath: res.data.path,
                  currentCardIndex: index,
                  generatorCardImagePath: ""
                });
              } else {
                utils.message(res.message);
              }
            })
            .catch(res => {
              wx.hideLoading();
            });
        }
      });
    } else {
      this.setData({
        currentCardIndex: index,
        customCardImagePath: ""
      });
    }
  },
  inputEvent(event) {
    let key = event.target.dataset.key;
    let value = event.detail.value.trim();
    this.setData(
      {
        ["detail." + key + ".value"]: value
      },
      () => {}
    );
  },
  getUserInfo(e) {
    if (e.detail.userInfo) {
      getApp().globalData["avatarUrl"] = e.detail.userInfo.avatarUrl;
      getApp().globalData["nickName"] = e.detail.userInfo.nickName;
      this.saveEdit();
    } else {
      utils.message("必须通过授权才能保存当前名片");
    }
  },
  saveEdit() {
    const _this = this;

    let requierList = [
      "name",
      "company",
      "position",
      "mobile",
      "address",
      "email"
    ];
    const data = this.data.detail;
    let flag = true;
    const lengthNum = requierList.length;
    for (let i = 0; i < lengthNum; i++) {
      const index = requierList[i];
      // console.log(cardFields[index].name, data[index].value)
      if (data[index].value.length === 0) {
        wx.showToast({
          icon: "none",
          title: cardFields[index].name + "不能为空"
        });
        flag = false;
        break;
      }
    }
    if (!flag) {
      return false;
    }
    wx.showLoading({
      mask: true,
      title: "正在保存..."
    });
    if (
      this.data.currentCardIndex !== "custom" &&
      this.data.currentCardIndex !== "-1"
    ) {
      // 只有当用户点击了名片模板的时候才需要生成图片
      // this.generatorImage()
      utils
        .generatorImage(
          wx.createCanvasContext("canvas", this),
          this.data.detail,
          this.data.currentCardIndex
        )
        .then(res => {
          console.log(res);
          utils
            .ajax(
              "/v1/bcs/uploadCustBusinessCard.do",
              // "http://localhost/index.php",
              {},
              {
                name: "businessCardFile",
                path: res.tempFilePath
              }
            )
            .then(res => {
              if (res.code === "000000") {
                // 图片上传成功
                _this.setData(
                  {
                    generatorCardImagePath: res.data.path
                  },
                  () => {
                    _this.saveRealData();
                  }
                );
              } else {
                // 图片上传失败
                wx.hideLoading();
                utils.message(res.message || "图片上传失败");
              }
            })
            .catch(err => {
              wx.hideLoading();
            });
        })
        .catch(res => {
          wx.hideLoading();
          utils.message("生成图片失败，请稍后重试");
        });
    } else {
      // 其他时间只需要保存信息即可
      this.saveRealData();
    }
  },
  saveRealData() {
    if (!this.data.customCardImagePath && !this.data.generatorCardImagePath) {
      utils.message("请选择模板");
      return false;
    }
    const _this = this;
    let detail = _this.data.detail;
    let postData = {
      name: detail.name.value, // 	64	是	姓名
      mobile: detail.mobile.value, // 	20	是	手机
      compName: detail.company.value, // 	64	是	公司名称
      subCompName: detail.subCompName.value, // 	64	否	子公司名称
      compDesc: detail.compDesc.value, // 	140		公司描述
      position: detail.position.value, // 	64	是	职位
      mail: detail.email.value, // 	128	否	邮件
      phone: detail.phone.value, // 	64	否	电话
      address: detail.address.value, // 	128	是	地址
      fax: detail.fax.value, // 	64	否	传真
      webSite: detail.webSite.value, // 	128	否	网站
      avatarUrl: getApp().globalData["avatarUrl"], // 	128	是	头像 wx.getUserInfo中获得
      weixin: detail.wechat.value, // 	64	否	微信号
      qq: detail.qq.value, // 	64	否	QQ号
      postCode: detail.postCode.value, // 	6	否	邮编
      customerPicturePath: this.data.generatorCardImagePath, // 	128	否	自定义名片路径url
      orginPicturePath: this.data.customCardImagePath, // 	128	是	证件上传url
      customerPicturePosition: this.data.currentCardIndex
    };
    console.log(postData);
    let url;
    if (_this.data.cardId == "") {
      // 创建自己的新名片
      url = "/v1/bcs/createUserCard.do";
    }
    if (_this.data.cardId == "other") {
      // 扫描别人的名片
      url = "/v1/bcs/createUserHolderCard.do";
      postData.cardId = _this.data.cardId;
    }
    if (_this.data.cardId != "" && _this.data.cardId != "other") {
      // 修改自己的名片
      url = "/v1/bcs/updateBusinessCard.do";
      postData.cardId = _this.data.cardId;
    }
    utils
      .ajax(url, postData)
      .then(res => {
        wx.hideLoading();
        if (res.code === "000000") {
          utils.message("保存成功");
          wx.hideLoading();
          wx.navigateBack({
            delta: 1
          });
        } else {
          utils.message(res.message || "保存名片失败");
        }
      })
      .catch(res => {
        wx.hideLoading();
        console.log("保存名片失败");
      });
  },
  updateDetail(options) {
    this.setData({
      cardId: options.cardId || "",
      ["detail.name.value"]: options.name || "",
      ["detail.mobile.value"]: options.mobile || "",
      ["detail.company.value"]: options.compName || "",
      ["detail.position.value"]: options.position || "",
      ["detail.address.value"]: options.address || "",
      ["detail.email.value"]: options.mail || "",
      ["detail.wechat.value"]: options.weixin || "",
      ["detail.phone.value"]: options.phone || "",
      ["detail.subCompName.value"]: options.subCompName || "",
      ["detail.site.value"]: options.webSite || "",
      ["detail.qq.value"]: options.qq || "",
      ["detail.postCode.value"]: options.postCode || "",
      ["detail.compDesc.value"]: options.compDesc || "",
      ["detail.fax.value"]: options.fax || "",
      customCardImagePath: options.orginPicturePath || "",
      generatorCardImagePath: options.customerPicturePath || "",
      currentCardIndex: options.customerPicturePosition || "1" // 如果没有这个值会自动使用0，主要用于首页新建名片
      // currentCardIndex: "0" // 如果没有这个值会自动使用0，主要用于首页新建名片
    });
  },
  onLoad: function(options) {
    console.log("options", options);
    this.updateDetail(options);
  },
  ...utils.defaultShare,
  onShow() {
    utils
      .preCheck(true)
      .then(res => {
        if (this.data.cardId != "" && this.data.cardId != "other") {
          this.getCardInfo();
        }
      })
      .catch(res => {});
  },
  getCardInfo() {
    utils
      .ajax("/v1/bcs/getBusinessCardWithHoldState.do", {
        cardId: this.data.cardId
      })
      .then(res => {
        if (res.code === "000000") {
          let detail = res.data.cardInfo;
          console.log("getApp().globalData", getApp().globalData);
          if (detail.createBy == wx.getStorageSync("userId")) {
            detail.createByMe = true;
          } else {
            detail.createByMe = false;
          }
          if (detail.cardId == getApp().globalData["myCards"][0]["cardId"]) {
            detail.isMine = true;
          } else {
            detail.isMine = false;
          }
          console.log(detail);
          this.updateDetail(detail);
        } else {
          console.log(res.message || "获取持有状态信息失败");
        }
      })
      .catch(res => {});
  }
});
